#include "include/muduo/net/EventLoop.h"
#include "include/muduo/net/Callbacks.h"
#include "include/muduo/net/TcpServer.h"
#include <iostream>
#include <unordered_map>
class TranslateServer{
public:
    TranslateServer(int port)
        :_server(&_baseloop,muduo::net::InetAddress("0.0.0.0",port),"Translate",muduo::net::TcpServer::kReusePort)
    {
        // 设置建立连接时的回调函数
        _server.setConnectionCallback(std::bind(&TranslateServer::OnConection, this, std::placeholders::_1));
        // 设置收到消息时的回调函数
        _server.setMessageCallback(std::bind(&TranslateServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    void start()
    {
        _server.start();
        _baseloop.loop();
    }
private:
    void OnConection(const muduo::net::TcpConnectionPtr& conn){
        // 新连接尽力成功时的回调函数
        if(conn->connected()){
            std::cout << "建立连接成功\n";
        }else{
            std::cout << "建立连接失败\n";
        }
    }
    std::string translate(const std::string& str){
        std::unordered_map<std::string,std::string> mp = {
            {"apple", "苹果"},
            {"banana", "香蕉"},
            {"car", "汽车"}
        };
        if(mp.count(str)) return mp[str];
        else return "unknown";
    }
    void OnMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp){
        // 通信连接收到请求时的回调函数
        std::string str = buf->retrieveAllAsString();
        std::string resp = translate(str);
        conn->send(resp);
    }
private:
    muduo::net::TcpServer _server;
    muduo::net::EventLoop _baseloop;
};
int main()
{
    TranslateServer svr(8080);
    svr.start();

    return 0;
}
